package org.maylove.wuziqi.timer;

import org.maylove.wuziqi.common.CustomEvent;
import org.maylove.wuziqi.common.EventMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Timer;
import java.util.TimerTask;

@Service
public class TimerService {

    private final ApplicationEventPublisher applicationEventPublisher;
    private Timer timer;

    @Autowired
    public TimerService(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void scheduleEvent(int seconds, EventMessage<Object> test) {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                applicationEventPublisher.publishEvent(new CustomEvent(this, test));
            }
        }, seconds * 1000);
    }

    public void cancelEvent() {
        if (timer!= null) {
            timer.cancel();
            timer = null;
        }
    }
}